package com.framework.modules.base.service.impl;

import java.util.Date;
import java.util.Map;
import java.util.UUID;

import com.framework.common.utils.DateUtils;
import com.framework.modules.base.entity.UserEntity;
import com.framework.modules.base.entity.UserInfoEntity;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.framework.modules.base.dao.TokenDao;
import com.framework.modules.base.entity.TokenEntity;
import com.framework.modules.base.service.TokenService;

@Service("tokenService")
public class TokenServiceImpl extends ServiceImpl<TokenDao, TokenEntity> implements TokenService {
	/**
	 * 秒数
	 */
	private final static int EXPIRE = 3600 * 24 * 30;

	@Override
	public TokenEntity queryByToken(String token,String platform) {
		return this.selectOne(new EntityWrapper<TokenEntity>().eq("token", token).eq("platform",platform));
	}

	@Override
	public Map<String,Object> getUserinfo(String token,String platform){
		return baseMapper.getUserinfo(token,platform);
	}

	@Override
	public TokenEntity createToken(long userId,String platform) {
		// 当前时间
		Date now = new Date();
		// 过期时间
		Date expireTime = DateUtils.addDateSeconds(now,EXPIRE);

		// 生成token
		String token = generateToken();

		// 保存或更新用户token
		TokenEntity tokenEntity = new TokenEntity();
		tokenEntity.setUserId(userId);
		tokenEntity.setToken(token);
		tokenEntity.setPlatform(platform);
		tokenEntity.setUpdateTime(now);
		tokenEntity.setExpireTime(expireTime);
		this.baseMapper.insertOrUpdateByUserIdAndPlatform(tokenEntity);
		return tokenEntity;
	}

	@Override
	public void expireToken(long userId,String platform) {
		Date now = new Date();
		TokenEntity tokenEntity = new TokenEntity();
		tokenEntity.setUserId(userId);
		tokenEntity.setPlatform(platform);
		tokenEntity.setUpdateTime(now);
		tokenEntity.setExpireTime(now);
		this.insertOrUpdate(tokenEntity);
	}

	private String generateToken() {
		return UUID.randomUUID().toString().replace("-", "");
	}


}
